package com.tdam2014.grupo3;

import java.util.ArrayList;

import android.app.ListFragment;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tdam2014.grupo3.adapters.PeopleAdapter;
import com.tdam2014.grupo3.db.DatabaseHelper;
import com.tdam2014.grupo3.db.PeopleDatabaseHelper;
import com.tdam2014.grupo3.db.PhotoDatabaseHelper;
import com.tdam2014.grupo3.db.PhotoSetDatabaseHelper;
import com.tdam2014.grupo3.entities.People;
import com.tdam2014.grupo3.entities.PhotoSet;
import com.tdam2014.grupo3.interfaces.PeopleSelectionListener;
import com.tdam2014.grupo3.tasks.DeletePeopleImagesTask;
import com.tdam2014.grupo3.tasks.FindPeopleTask;
import com.tdam2014.grupo3.utils.NetworkUtils;

public class PeopleFragment extends ListFragment {
	
	private PeopleSelectionListener peopleSelectionListener;
	
	private TextView txtUsername;
	private FindPeopleTask findPeopleTask;

	public PeopleFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_people, container, false);
		
		((TextView) ((RelativeLayout) rootView.findViewById(R.id.lloHeaderNewUser)).findViewById(R.id.header)).setText(R.string.follow_new_user);
		((TextView) ((RelativeLayout) rootView.findViewById(R.id.lloHeaderUsersExplored)).findViewById(R.id.header)).setText(R.string.followed_users);
		
		txtUsername = (TextView) rootView.findViewById(R.id.txtNewUsername);
		
		return rootView;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		ArrayList<People> peoples = new PeopleDatabaseHelper(getActivity()).getPeopleList();
		
		final PeopleAdapter peopleAdapter = new PeopleAdapter(getActivity());
		peopleAdapter.setPeoples(peoples);
		setListAdapter(peopleAdapter);
		
		registerForContextMenu(getListView());
		
		// Click Listener para los items de la lista
		getListView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				People people = (People) peopleAdapter.getItem(position);
				peopleSelectionListener.onPeopleSelected(people);
			}
		});
		
		// Click Listener para el boton de nuevo usuario
		ImageButton searchPeople = (ImageButton) getView().findViewById(R.id.imbSearchNewUser);
		searchPeople.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(String.valueOf(txtUsername.getText()).isEmpty()) {
					Toast error = Toast.makeText(getActivity(), getResources().getString(R.string.insert_username), Toast.LENGTH_SHORT);
					error.show();
				} else {
					String newUsername = String.valueOf(txtUsername.getText()).toLowerCase();
					
					PeopleDatabaseHelper peopleDatabaseHelper = new PeopleDatabaseHelper(getActivity());
					People people = peopleDatabaseHelper.getPeopleByUsername(newUsername);
					
					if(people != null) peopleSelectionListener.onPeopleSelected(people);
					else searchUser(newUsername);
				}
			}
		});
	}
	
	@Override
	public PeopleAdapter getListAdapter() {
		return (PeopleAdapter) super.getListAdapter();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getActivity().getMenuInflater();
	    inflater.inflate(R.menu.people_context_menu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    switch (item.getItemId()) {
	        case R.id.noExploreUser:
	        	People selectedPeople = ((PeopleAdapter) getListAdapter()).getItem(info.position);
	        	
	        	// Cargo los PhotoSets
	        	PhotoSetDatabaseHelper photoSetDatabaseHelper = new PhotoSetDatabaseHelper(getActivity());
	        	selectedPeople.setPhotoSets(photoSetDatabaseHelper.getPhotoSetList(selectedPeople.getNsid()));
	        	
	        	// A cada PhotoSet le cargo las Photos
	        	PhotoDatabaseHelper photoDatabaseHelper = new PhotoDatabaseHelper(getActivity());
	        	for (PhotoSet photoSet : selectedPeople.getPhotoSets()) {
	        		photoSet.setPhotos(photoDatabaseHelper.getPhotoList(photoSet.getId(), DatabaseHelper.colPhotoID));
	        	}
	        	
	            PeopleDatabaseHelper peopleDatabaseHelper = new PeopleDatabaseHelper(getActivity());
	            peopleDatabaseHelper.deletePeople(selectedPeople.getNsid());
	            
	            getListAdapter().removeItem(info.position);
	            getListAdapter().notifyDataSetChanged();
	            
	            DeletePeopleImagesTask deletePeopleImagesTask = new DeletePeopleImagesTask();
	            deletePeopleImagesTask.execute(selectedPeople);
	            
	            Toast t = Toast.makeText(getActivity(), getResources().getString(R.string.delete_user) + " " + selectedPeople.getRealName(), Toast.LENGTH_SHORT);
	            t.show();
	    }
	    
	    return true;
	}
	
	public void setPeopleSelectionListener(
			PeopleSelectionListener peopleSelectionListener) {
		this.peopleSelectionListener = peopleSelectionListener;
	}
	
	private void searchUser(String newUsername) {
		if (NetworkUtils.isOnline(getActivity())) {
			findPeopleTask = new FindPeopleTask(this);
			findPeopleTask.execute(newUsername);
		} else {
			Toast toast = Toast.makeText(getActivity(), getResources().getString(R.string.not_connected), Toast.LENGTH_SHORT);
			toast.show();
		}
	}
	
	public void endSearchUser(People people) {
		getListAdapter().addItem(people);
		getListAdapter().notifyDataSetChanged();
		
		peopleSelectionListener.onPeopleSelected(people);
	}
}